% =========================================================================
function out=log2exp(x); 
% 
% function out=log2exp(x); 
% X is a vector 
% This code computes 
% log( mean( exp(x) ) ) in cases where overflow might occur due to size 
% 
% Alejandro Justiniano October 31 2006 
% =========================================================================
t=length(x(:)); 
if t < 20 
    warning('Vector to small, be careful with overlap') 
end 
n=4; 
p=round(t*(linspace(0,1,n+1)));
x=sort(x); 
cmed=median(x); 

itcount=0;
flag_cont=0;
while flag_cont < 1;
    itcount=itcount+1;
    cons=zeros(n,1);
    switch itcount
        case 2
            cmed=median( x(p(4)+1:p(5)) );
        case 3
            temp=round(0.5*(p(4)+p(5)));
            cmed=median( x(temp:p(5)) );
        case 4
            cmed=median( x(p(1)+1:p(2)) );
        case 5
            temp=round(0.5*(1+p(2)));
            cmed=median( x(temp:p(2)) );
        case 6
            warning('Could not achieve non-zero')
    end
    vector=zeros(n,1);
    ii=1;
    for ii=1:n;
        cons(ii)=median( x( p(ii)+1 : p(ii+1) ) );
        %cons(ii)=x(p(ii)+1);
        vector(ii)=0.25*mean( exp( x( p(ii)+1:p(ii+1)  )-cons(ii) ) )*(exp(cons(ii)-cmed));
    end;
    if any(vector==0)==0 & any( isinf(vector) )==0 
        flag_cont=1; 
    end 
    if itcount > 5 
        break 
    end 
    out=log(sum(vector))+cmed;
end
orig=log(mean(exp(x))); 
if ~isinf(abs(orig)); 
    disp(['Maximum discrepancy: ',num2str(out-orig)]); 
else
    if isinf(abs(out));
        disp('Warning! Even with transformation obtain INFINITY'); 
    end
end 